local M = {}

local function init_dap_sign()
  --  local dap_install = require "dap-install"
  --  dap_install.setup {
  --    installation_path = vim.fn.stdpath "data" .. "/dapinstall/"
  --  }

  local dap_breakpoint = {
    error = {
      text = '☻',
      texthl = 'LspDiagnosticsSignError',
      linehl = '',
      numhl = '',
    },
    rejected = {
      text = '♬',
      texthl = 'LspDiagnosticsSignHint',
      linehl = '',
      numhl = '',
    },
    stopped = {
      text = '■',
      texthl = 'LspDiagnosticsSignInformation',
      linehl = 'DiagnosticUnderlineInfo',
      numhl = 'LspDiagnosticsSignInformation',
    },
  }

  vim.fn.sign_define('DapBreakpoint', dap_breakpoint.error)
  vim.fn.sign_define('DapStopped', dap_breakpoint.stopped)
  vim.fn.sign_define('DapBreakpointRejected', dap_breakpoint.rejected)
end

local function init_dap_view()
  -- dapui config
  local dap, dapui, _ =
    require 'dap', require 'dap.dap_ui', require 'dap.dap_virtual_text'

  dap.set_log_level 'TRACE'

  dap.listeners.after.event_initialized['dapui_config'] = function()
    dapui.open()
    vim.api.nvim_command 'DapVirtualTextEnable'
    -- dapui.close("tray")
  end
  dap.listeners.before.event_terminated['dapui_config'] = function()
    vim.api.nvim_command 'DapVirtualTextDisable'
    dapui.close()
  end
  dap.listeners.before.event_exited['dapui_config'] = function()
    vim.api.nvim_command 'DapVirtualTextDisable'
    dapui.close()
  end
  -- for some debug adapter, terminate or exit events will no fire, use disconnect reuest instead
  dap.listeners.before.disconnect['dapui_config'] = function()
    vim.api.nvim_command 'DapVirtualTextDisable'
    dapui.close()
  end
  -- TODO: wait dap-ui for fix temrinal layout
  -- the "30" of "30vsplit: doesn't work
  dap.defaults.fallback.terminal_win_cmd = '30vsplit new' -- this will be override by dapui
end

local function init_dap_lang()
  -- load from json file
  require('dap.ext.vscode').load_launchjs(nil, { cppdbg = { 'cpp' } })

  -- require("dap.dap-cpp")
  -- require("dap.dap-rust")
  require 'dap.debug.go'
  require 'dap.debug.cpp-lldb'
  require('dap.debug.lua').setup()
end

function M.setup()
  init_dap_sign()
  init_dap_view()
  init_dap_lang() -- Debugger
  require('keymap').debug()
end

-- debug nvim ,log at ~/.cache/nvim/lsp.log
-- vim.lsp.set_log_level 'debug'

return M
